﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class krj_document_download : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {

  }
  protected void gv_document_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
      Label lbl_UPD_DATE = e.Row.FindControl("lbl_UPD_DATE") as Label;
      Label lbl_UPD_TIME = e.Row.FindControl("lbl_UPD_TIME") as Label;
      lbl_UPD_DATE.Text = CommonUtil.TransferyyyyMMddToDate(lbl_UPD_DATE.Text);
      lbl_UPD_TIME.Text = CommonUtil.TransferhhmmssToTime(lbl_UPD_TIME.Text);

      Label lbl_path = e.Row.FindControl("lbl_ISPATH") as Label;
      lbl_path.Text = Path.GetFileName(Server.MapPath(lbl_path.Text));

      if (string.IsNullOrEmpty(lbl_path.Text))
      {
        ImageButton ib_download = e.Row.FindControl("ib_download") as ImageButton;
        ib_download.Visible = false;
      }
    }
  }

  protected void gv_document_SelectedIndexChanged(object sender, EventArgs e)
  {   
    lbl_message.Text = "";

    Label lbl_path = gv_document.SelectedRow.FindControl("lbl_filepath") as Label;
    Label lbl_DOCUMENT_NO = gv_document.SelectedRow.FindControl("lbl_DOCUMENT_NO") as Label;
    if (!string.IsNullOrEmpty(txt_user_no.Text))
    {
      using (MISEntities mis = new MISEntities())
      {
        if (mis.MIS_USER_AP.Where(u => u.USER_ID == txt_user_no.Text).Count() == 0)
        {
          CommonUtil.DisplayErrorMessage("職工代號不正確，無此員工!請重試!", lbl_message);
          return;
        }
      }
    }
    string user_no = string.IsNullOrEmpty(txt_user_no.Text) ? User.Identity.Name : txt_user_no.Text;

    KRJEntities dc = new KRJEntities();

    var document = dc.KRJ_DOCUMENT.Where(d => d.DOCUMENT_NO == lbl_DOCUMENT_NO.Text).Single();
    string newseq = document.UPD_DOCUMENT_NO;
    try
    {

      if (document.ISMAIL == "Y") //是否信件通知
      {
        MISEntities mis = new MISEntities();
        var user = mis.MIS_USER_AP.Where(u => u.USER_ID == user_no).SingleOrDefault();
        if (user != null)
        {
          var dept_id = user.DEPT_ID;//使用者部門
          var dept = mis.MIS_DEPT_AP.Where(d => d.DEPT_ID == dept_id).SingleOrDefault();
          if (dept != null)
          {
            string master_mail = dept.E_MAIL; //取得站所MAIL
            if (string.IsNullOrEmpty(master_mail))
            {
              var master_id = dept.USER_ID; //主管編號
              if (!string.IsNullOrEmpty(master_id))
              {
                var master_user = mis.MIS_USER_AP.Where(u => u.USER_ID == master_id).SingleOrDefault(); //主管物件
                if (master_user != null)
                  master_mail = string.IsNullOrEmpty(master_user.E_MAIL1) ? master_user.E_MAIL2 : master_user.E_MAIL1; //主管MAIL                            
              }
            }

            if (!string.IsNullOrEmpty(master_mail))
            {
              //只有嘉里大榮的MAIL才送
              if (master_mail.ToLower().Contains("@kerrytj.com"))
              {
                //Send Mail To Master
                //PanelMail.Visible = true;
                //lbl_receiver.Text = user.USER_NAME;
                //lbl_form.Text = document.DOCUMENT_NAME;
                string mailhtml = "親愛的主管 您好： <BR/>  您的同仁：" +
                      user.USER_NAME +
                      " 下載了[" + document.DOCUMENT_NAME + "]表單，敬請知悉，謝謝!<BR/>" +
                      "KerryTJ System.";
                MailUtil.SendHTMLMail("service@kerrytj.com", master_mail, "表單下載通知", mailhtml);
                //PanelMail.Visible = false;
              }
            }

            //送MAIL給承辦人
            if (!string.IsNullOrEmpty(document.UNDERTAKERS))
            {
              var taker = mis.MIS_USER_AP.Where(u => u.USER_ID == document.UNDERTAKERS).SingleOrDefault();
              if (taker != null)
              {
                string taker_mail = string.IsNullOrEmpty(taker.E_MAIL1) ? taker.E_MAIL2 : taker.E_MAIL1;
                if (!string.IsNullOrEmpty(taker_mail))
                {
                  //只有嘉里大榮的MAIL才送
                  if (taker_mail.ToLower().Contains("@kerrytj.com"))
                  {
                    //Send Mail To Taker                 
                    string mailhtml = "親愛的承辦人 您好： <BR/> " +
                      dept.DEPT_NAME + "-" + user.USER_NAME +
                      " 下載了[" + document.DOCUMENT_NAME + "]表單，敬請知悉，謝謝!<BR/>" +
                      "KerryTJ System.";
                    MailUtil.SendHTMLMail("service@kerrytj.com", taker_mail, "表單下載通知", mailhtml);
                 
                  }
                }
              }
            }
          }
        }
      }


     string sourceFileName = System.IO.Path.GetFileName(Server.MapPath(document.ISPATH));
     string sourceFileNameWithoutExtension =
       System.IO.Path.GetFileNameWithoutExtension(Server.MapPath(document.ISPATH));
      string tempPath = "~/Document/FormUploadsTemp/"
        + DateTime.Now.ToString("yyyyMMdd-hhmmss-fff-")
        + sourceFileName;

      string pdfFileName = sourceFileNameWithoutExtension + ".pdf";
      
      //var tempfiles = from f in System.IO.Directory.GetFiles(System.IO.Path.GetDirectoryName(Server.MapPath(tempPath)))
      //                where f.Contains(sourceFileNameWithoutExtension)
      //                select f;
      //foreach (var tfile in tempfiles)
      //{
      //  System.IO.File.Delete(tfile);
      //}

      //將欲下載的檔案先存放至TEMP中，以進行寫序號或轉PDF
      System.IO.File.Copy(Server.MapPath(document.ISPATH), Server.MapPath(tempPath), true);

      if (document.ISSEQUENCE == "Y") //是否編列序號
      {
        if (document.DOWNLOAD_YEAR != DateTime.Now.ToString("yyyy"))
        {
          newseq = "000000";
        }

        string update_seq = (int.Parse(newseq) + 1).ToString().PadLeft(6, System.Convert.ToChar("0"));
        document.UPD_DOCUMENT_NO = update_seq;
        document.DOWNLOAD_YEAR = DateTime.Now.ToString("yyyy");
        dc.SaveChanges();
       
        //寫入Word頁尾
        string extension = System.IO.Path.GetExtension(Server.MapPath(document.ISPATH));
        if (extension == ".doc" || extension == ".docx")
        {
          string footer = DateTime.Now.AddYears(-1911).ToString("yyy") + "年嘉大人字第" + update_seq + "號";
          FileUtil.WriteHeaderAndFooterToWord(Server.MapPath(tempPath), "", footer);                    
        }        
      }    

      if (document.ISSTATISTICS == "Y") //是否統計下載人數
      {
        //先取目前log此文件的最大統計人數
        string log_seq = "000000";
        var log = dc.KRJ_DOCUMENT_LOG
              .Where(l => l.DOCUMENT_NO == document.DOCUMENT_NO)             
              .OrderByDescending(l => l.DOCUMENT_SEQ)
              .FirstOrDefault();
        if (log != null)
        {
          log_seq = log.DOCUMENT_SEQ;
        }

        KRJ_DOCUMENT_LOG document_log = new KRJ_DOCUMENT_LOG();
        document_log.DOCUMENT_CATEGORY = document.DOCUMENT_CATEGORY;
        document_log.DOCUMENT_NO = document.DOCUMENT_NO;
        document_log.DOCUMENT_NAME = document.DOCUMENT_NAME;
        document_log.DOCUMENT_SEQ = (int.Parse(log_seq) + 1).ToString().PadLeft(6, System.Convert.ToChar("0")); 
        document_log.USER_ID = user_no;
        document_log.CRT_ID = User.Identity.Name;
        document_log.CRT_DATE = DateTime.Now.ToString("yyyyMMdd");
        document_log.CRT_TIME = DateTime.Now.ToString("hhmmss");
        document_log.UPD_ID = User.Identity.Name;
        document_log.UPD_DATE = DateTime.Now.ToString("yyyyMMdd");
        document_log.UPD_TIME = DateTime.Now.ToString("hhmmss");
        dc.KRJ_DOCUMENT_LOG.Add(document_log);
        dc.SaveChanges();
      }

      CommonUtil.DisplayInfoMessage("表單：" + lbl_path.Text + "下載完成!", lbl_message);


      if (document.ISTRANSFORM == "Y") //是否轉PDF檔
      {
        int index = tempPath.LastIndexOf(".");
        string PDFFile = tempPath.Substring(0, index) + ".pdf";               
        FileUtil.ConvertWordToPDF(Server.MapPath(tempPath), Server.MapPath(PDFFile));
        FileUtil.DownloadFile(Server.MapPath(PDFFile), pdfFileName);
      }

      //執行檔案下載
      FileUtil.DownloadFile(tempPath, sourceFileName);
    }
    catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
    {
      CommonUtil.DisplayErrorMessage(dbex.Message, lbl_message);
    }
    catch (Exception ex)
    {
      CommonUtil.DisplayErrorMessage(ex.Message, lbl_message);
      //CommonUtil.DisplayErrorMessage("其他使用者正在下載此文件，請稍後再試! 謝謝", lbl_message);
    }
  }
}